import "./bill.css";
import moment from "moment";
import {
  Button,
  DatePicker,
  Select,
  Table,
  Space,
  Modal,
  Form,
  Input,
  Radio,
  message,
  Popconfirm,
} from "antd";
import { useEffect, useState, useRef } from "react";
const { Option } = Select;
const Bill = () => {
  let myForm = useRef();
  let myFormTwo = useRef();
  const columns = [
    {
      title: "日期",
      dataIndex: "date",
      key: "date",
      render: (text) => <span>{text}</span>,
    },
    {
      title: "金额",
      dataIndex: "money",
      key: "money",
    },
    {
      title: "分类",
      dataIndex: "type",
      key: "type",
    },
    {
      title: "备注",
      key: "recommend",
      dataIndex: "recommend",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => {
              editItem(record);
            }}
          >
            修改
          </Button>
          <Popconfirm
            title="确定删除麽？"
            okText="确定"
            cancelText="取消"
            onConfirm={() => {
              confirmDelete(record);
            }}
            onCancel={cancelDelete}
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const editItem = (record) => {
    setIsModalVisibleTwo(true);
    setTimeout(() => {
      seteditKey(record.key);
      myFormTwo.current.setFieldsValue({
        money: parseInt(record.money),
        date: moment(record.date),
        type: record.type,
        recommend: record.recommend,
      });
    }, 0);
  };

  const confirmDelete = (record) => {
    console.log(record, "record");
    let data = JSON.parse(localStorage.getItem("Data"));
    for (let i = 0; i < data.length; i++) {
      if (data[i].key === record.key) {
        data.splice(i, 1);
      }
    }
    localStorage.setItem("Data", JSON.stringify(data));
    message.success("删除成功");
    getData();
  };

  const cancelDelete = () => {
    console.log("取消删除");
  };
  const onChange = (date, dateString) => {
    console.log(date, dateString, "月份");
    setfilterMonth(dateString);
  };
  const handleChange = (value) => {
    console.log(`selected ${value}`);
    setfilterType(value);
  };

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalVisibleTwo, setIsModalVisibleTwo] = useState(false);

  const [value, setValue] = useState("早餐");

  const [ops, setops] = useState(1);

  const [editKey, seteditKey] = useState(0);

  useEffect(() => {
    setops(1);
    getData();
  }, []);

  const [Data, setData] = useState([]);

  const [filterMonth, setfilterMonth] = useState("");
  const [filterType, setfilterType] = useState("");

  const getData = () => {
    if (localStorage.getItem("Data")) {
      setData(JSON.parse(localStorage.getItem("Data")));
    }
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const onFinishTwo = (values) => {
    console.log("编辑成功");
    values.key = editKey;
    let time = new Date(values.date._d);
    let y = time.getFullYear();
    let m = time.getMonth() + 1;
    let d = time.getDate();
    let h = time.getHours();
    let min = time.getMinutes();
    let sec = time.getSeconds();
    if (m <= 9) {
      m = "0" + m;
    }
    let timeString = y + "-" + m + "-" + d + " " + h + ":" + min + ":" + sec;
    values.date = timeString;
    console.log(values, editKey, "aaaaa");
    let data = JSON.parse(localStorage.getItem("Data"));
    for (let i = 0; i < data.length; i++) {
      if (data[i].key === editKey) {
        data.splice(i, 1);
        data.splice(i, i, values);
      }
    }
    console.log(data, "data");
    localStorage.setItem("Data", JSON.stringify(data));
    getData();
    message.success("编辑成功");
    setIsModalVisibleTwo(false);
    seteditKey(0);
  };

  const onFinishFailedTwo = (error) => {
    console.log(error, "error");
    console.log("编辑失败");
  };

  const onFinish = (values) => {
    console.log(myForm, "myFormmyForm");
    values.key = Math.floor(Math.random() * 1000);
    let time = new Date(values.date._d);
    let y = time.getFullYear();
    let m = time.getMonth() + 1;
    let d = time.getDate();
    let h = time.getHours();
    let min = time.getMinutes();
    let sec = time.getSeconds();
    if (m <= 9) {
      m = "0" + m;
    }
    // if (d <= 9) {
    //   d = "0" + d;
    // }
    let timeString = y + "-" + m + "-" + d + " " + h + ":" + min + ":" + sec;
    values.date = timeString;
    let copyData;
    if (localStorage.getItem("Data")) {
      copyData = JSON.parse(localStorage.getItem("Data"));
    } else {
      copyData = [];
    }
    copyData.push(values);
    console.log(copyData, copyData, "copyData");
    localStorage.setItem("Data", JSON.stringify(copyData));
    message.success("记账成功");
    getData();
    setIsModalVisible(false);
    myForm.current.resetFields();
  };

  const reset = () => {
    let data = JSON.parse(localStorage.getItem("Data"));
    message.success('重置成功')
    setfilterMonth('')
    setfilterType('')
    setData(data);
  }

  const filter = () => {
    let data = JSON.parse(localStorage.getItem("Data"));
    if (filterMonth === "" && filterType === "") {
      message.error("至少选择一个筛选条件");
      return;
    }
    if (filterMonth !== "" && filterType === "") {
      data = data.filter((item) => {
        return item.date.slice(0, 7) === filterMonth;
      });
    }
    if (filterMonth === "" && filterType !== "") {
      data = data.filter((item) => {
        return item.type === filterType;
      });
    }
    if (filterMonth !== "" && filterType !== "") {
      data = data.filter((item) => {
        return  item.date.slice(0, 7) === filterMonth && item.type === filterType;
      });
    }
    message.success('筛选成功')
    setfilterMonth('')
    setfilterType('')
    setData(data);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  const onOk = (value) => {
    console.log("onOk: ", value);
  };

  const onChangeType = (e) => {
    console.log("radio checked", e.target.value);
    setValue(e.target.value);
  };
  return (
    <div className="bill">
      <div className="head">
        <div>
          <DatePicker
            onChange={onChange}
            picker="month"
            placeholder="选择月份"
          />
        </div>
        <div>
          <Select
            style={{ width: 120 }}
            onChange={handleChange}
            placeholder="选择分类"
            allowClear
          >
            <Option value="早餐">早餐</Option>
            <Option value="电子">电子</Option>
            <Option value="工资">工资</Option>
            <Option value="理财">理财</Option>
            <Option value="衣物">衣物</Option>
            <Option value="其他">其他</Option>
          </Select>
        </div>
        <div>
          <Button
            type="primary"
            onClick={() => {
              filter();
            }}
          >
            查询
          </Button>
        </div>
        <div>
          <Button onClick={()=>{reset()}}>重置</Button>
        </div>
      </div>
      <div className="center">
        <Button
          type="primary"
          onClick={() => {
            showModal();
          }}
        >
          记一笔
        </Button>
      </div>
      <div className="bottom">
        <Table columns={columns} dataSource={Data} pagination={false} />
        {/* <div>共 100 条数据</div> */}
      </div>
      <div className="modal">
        {/* initialValues={{ type: value }} //设置数据回显 */}
        <Modal
          title="记一笔"
          visible={isModalVisible}
          footer={false}
          onCancel={() => {
            setIsModalVisible(false);
          }}
        >
          <Form
            ref={myForm}
            layout="vertical"
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="金额"
              name="money"
              rules={[
                {
                  required: true,
                  message: "请输入金额 负数为支出 正数为收入!",
                },
              ]}
            >
              <Input placeholder="请输入金额 负数为支出 正数为收入" type="number" />
            </Form.Item>

            <Form.Item
              label="日期"
              name="date"
              rules={[
                {
                  required: true,
                  message: "请选择日期!",
                },
              ]}
            >
              <DatePicker placeholder="请选择日期" showTime onOk={onOk} />
            </Form.Item>

            <Form.Item
              label="分类"
              name="type"
              rules={[
                {
                  required: true,
                  message: "请选择分类!",
                },
              ]}
            >
              <Radio.Group onChange={onChangeType} value={value}>
                <Radio value="早餐">早餐</Radio>
                <Radio value="电子">电子</Radio>
                <Radio value="工资">工资</Radio>
                <Radio value="理财">理财</Radio>
                <Radio value="衣物">衣物</Radio>
                <Radio value="其他">其他</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              label="备注"
              name="recommend"
              rules={[
                {
                  required: true,
                  message: "请输入备注!",
                },
              ]}
            >
              <Input.TextArea
                placeholder="请输入备注"
                maxLength={200}
              ></Input.TextArea>
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 0,
                span: 16,
              }}
            >
              <Button
                type="default"
                className="marginRight"
                onClick={() => {
                  setIsModalVisible(false);
                }}
              >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title="记一笔修改"
          visible={isModalVisibleTwo}
          footer={false}
          onCancel={() => {
            setIsModalVisibleTwo(false);
            //   myFormTwo.current.resetFields();
          }}
        >
          <Form
            ref={myFormTwo}
            layout="vertical"
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            onFinish={onFinishTwo}
            onFinishFailed={onFinishFailedTwo}
            autoComplete="off"
          >
            <Form.Item
              label="金额"
              name="money"
              rules={[
                {
                  required: true,
                  message: "请输入金额!",
                },
              ]}
            >
              <Input placeholder="请输入金额 负数为支出 正数为收入" type="number" />
            </Form.Item>

            <Form.Item
              label="日期"
              name="date"
              rules={[
                {
                  required: true,
                  message: "请选择日期!",
                },
              ]}
            >
              <DatePicker placeholder="请选择日期" showTime onOk={onOk} />
            </Form.Item>

            <Form.Item
              label="分类"
              name="type"
              rules={[
                {
                  required: true,
                  message: "请选择分类!",
                },
              ]}
            >
              <Radio.Group onChange={onChangeType} value={value}>
                <Radio value="早餐">早餐</Radio>
                <Radio value="电子">电子</Radio>
                <Radio value="工资">工资</Radio>
                <Radio value="理财">理财</Radio>
                <Radio value="衣物">衣物</Radio>
                <Radio value="其他">其他</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              label="备注"
              name="recommend"
              rules={[
                {
                  required: true,
                  message: "请输入备注!",
                },
              ]}
            >
              <Input.TextArea
                placeholder="请输入备注"
                maxLength={200}
              ></Input.TextArea>
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 0,
                span: 16,
              }}
            >
              <Button
                type="default"
                className="marginRight"
                onClick={() => {
                  setIsModalVisibleTwo(false);
                  // myFormTwo.current.resetFields();
                }}
              >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </div>
  );
};

export default Bill;
